package org.vectrics.recruiter.struts.admin;

import java.util.Calendar;

import javax.servlet.jsp.JspException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.vectrics.SystemException;
import org.vectrics.common.util.DateSync;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.recruiter.RecruitServiceLocator;
import org.vectrics.recruiter.user.ResumeScanBatch;
import org.vectrics.recruiter.user.ResumeScanCriteria;
import org.vectrics.recruiter.user.resume.ResumeScanRun;
import org.vectrics.struts.Request;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;


public class ResumeScanBatchSaveAction extends VectricsStrutsAction {
    private transient final Log log = LogFactory.getLog(this.getClass());
	public static String JOB_ID_PARAM = "jobId";


	// Intercept 
	public String doExecute(VectricsActionData actionData)	throws JspException {
		log.debug("execute() - called");
		Request request = actionData.getRequest();
		ActionForm form = actionData.getForm();
		
		ResumeScanForm scanForm = (ResumeScanForm)form;
		
		String batchId = scanForm.getBatchId();
		if (batchId.length() <= 0 )
			batchId = null;
		if (actionData.wasButtonPressed("cancel") == false) {
			
			if (actionData.wasButtonPressed("delete") == true) {
				log.debug("User choose to delete this batch");
				ResumeScanBatch batch = null;
				if (batchId == null) {
				    log.debug("Batch does not exist yet, no deletion needed");
				} else {
				    batch = RecruitServiceLocator.getRecruitUserService().findResumeScanBatch(new Long(batchId));
					RecruitServiceLocator.getRecruitUserService().clearResumeScanResults(batch);
					RecruitServiceLocator.getRecruitUserService().removeResumeScanBatch(batch);
				}
				return ("success");
			} else {
				ResumeScanBatch batch = null;
				if (batchId == null) {
				    batch = new ResumeScanBatch();
				    batch.setDomain(ThreadProperties.getDomain());
				} else {
				    batch = RecruitServiceLocator.getRecruitUserService().findResumeScanBatch(new Long(batchId));
					RecruitServiceLocator.getRecruitUserService().clearResumeScanResults(batch);
					RecruitServiceLocator.getRecruitUserService().removeAllCriteria(batch);
					if (batch.getCriteriaList().size() > 0)
						throw new SystemException("Unexpected condition - after clearing criteria, criteria still exist for batch");
					
					// Resync batch after db clear of criteria.
				    batch = RecruitServiceLocator.getRecruitUserService().findResumeScanBatch(new Long(batchId));
				}
				batch.setDescription(scanForm.getDescription());
				Calendar expireDate = Calendar.getInstance();
				expireDate.add(Calendar.DATE, 2);
				batch.setExpireDate(expireDate.getTime());
				Integer maxResumeAge = new Integer(scanForm.getMaxResumeAge());
				batch.setMaxResumeAge(maxResumeAge);
				batch.setRunDate(DateSync.getCurrentTime());
				batch.setStatus(ResumeScanBatch.STATUS_NOT_RUN);
				batch.setRunPerson(actionData.getAuthPerson());
				batch.setMinimumCount(new Long(scanForm.getMinResultCount()));
				batch.setMaximumCount(new Long(scanForm.getMaxResultCount()));
				batch.setMinimumPercent(new Long(scanForm.getMinPercentage()));
				
				addCriteria(batch, scanForm.getWord1(), scanForm.getWeight1());
				addCriteria(batch, scanForm.getWord2(), scanForm.getWeight2());
				addCriteria(batch, scanForm.getWord3(), scanForm.getWeight3());
				addCriteria(batch, scanForm.getWord4(), scanForm.getWeight4());
				addCriteria(batch, scanForm.getWord5(), scanForm.getWeight5());
				addCriteria(batch, scanForm.getWord6(), scanForm.getWeight6());
				addCriteria(batch, scanForm.getWord7(), scanForm.getWeight7());
				addCriteria(batch, scanForm.getWord8(), scanForm.getWeight8());

				boolean runAfterSave = false;
				if (actionData.wasButtonPressed("saverun")) {
					runAfterSave = true;
					batch.setStatus(ResumeScanBatch.STATUS_RUNNING);
				}
				
				
				RecruitServiceLocator.getRecruitUserService().updateResumeScanBatch(batch);
		    	ThreadProperties.forcedCommitAndNewTransaction();
				
				if (runAfterSave) {
					ResumeScanRun runnable = new ResumeScanRun(batch.getDomain(), batch, request.getLocale());
					Thread scanThread = new Thread(runnable);
					scanThread.setName("Resume scan thread for batch: " + batch.getId());
					scanThread.setPriority(Thread.MIN_PRIORITY);
					scanThread.start();
				} else {
				}
				return ("success");
			}
		} else {
			return ("cancel");
		}
		
	}
	
	/**
	 * 
	 */
	private void addCriteria(ResumeScanBatch batch, String word, String weight) {
	    if ((word != null) && (word.trim().length() > 0)) {
		    ResumeScanCriteria criteria = new ResumeScanCriteria();
		    criteria.setPhrase(word);
		    criteria.setMatchCase(new Boolean(false));
		    criteria.setWeight(new Integer(weight));
		    batch.addCriteria(criteria);
	    }
	}
/*	
    public String getBatchId() {
        return batchId;
    }
    public void setBatchId(String batchId) {
        this.batchId = batchId;
    }
    */
}
